package com.gree.flowable.app.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.flowable.app.mapper.FormInfoMapper;
import com.gree.flowable.app.mapper.FormModelMapper;
import com.gree.flowable.app.mapper.plus.FormInfoService;
import com.gree.flowable.app.mapper.plus.FormModelService;
import com.gree.flowable.app.pojo.ex.FormInfoExModelArr;
import com.gree.flowable.app.pojo.form.FormInfo;
import com.gree.flowable.app.pojo.form.FormModel;
import com.gree.flowable.app.pojo.model.PagerModel;
import com.gree.flowable.app.pojo.model.Query;
import com.gree.flowable.app.pojo.to.FormTO;
import com.gree.flowable.app.pojo.to.QueryFormInfoTO;
import com.gree.flowable.app.pojo.vo.ReturnVO;
import com.gree.flowable.app.services.IFormInfoService;
import com.gree.flowable.app.tools.constants.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：180849
 * @date ：Created in 2021/3/30 16:48
 * @description：表单信息
 * @modified By：
 * @version: 1.0
 */
@Service
public class IFormInfoServiceImpl implements IFormInfoService {

    @Autowired
    private FormInfoMapper formInfoMapper;

//    @Autowired
//    private FormModelKeyMapper formModelKeyMapper;

    @Autowired
    private FormModelMapper formModelMapper;

    @Autowired
    private FormModelService formModelService;

    @Autowired
    private FormInfoService formInfoService;

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    /**
     * 添加自定义的表单
     *
     * @param formTO 自定义表单信息
     * @return 插入成功的条数
     */
    @Override
    public Integer addFormInfo(FormTO formTO) {
        String modelKey = formTO.getModelKey();
        Map form = formTO.getFormInfo();
        String formId = "key_"+System.currentTimeMillis();
        FormInfo formInfo = new FormInfo();
        formInfo.setFormInfo(String.valueOf(form));
        return formInfoMapper.insert(formInfo);
    }

    /**
     * 添加自定义的表单
     *
     * @param formInfo 自定义表单信息
     * @return 插入成功的条数
     */
    @Override
    public Boolean addFormInfoForString(FormInfo formInfo) {
//        formInfo.setFormId("key_"+System.currentTimeMillis());
        formInfo.setCreateTime(new Date());
        return formInfoService.saveOrUpdate(formInfo);
    }

    /**
     * 根据id查找表单信息
     *
     * @param formId 表单id
     * @return 表单的所有信息
     */
    @Override
    public FormInfo queryFormById(String formId) {
//        FormInfo formInfo = formInfoMapper.queryFormInfo(formId);
        FormInfo formInfo = formInfoMapper.selectById(formId);
        return formInfo;
    }

    /**
     * 删除表单模型
     *
     * @param formId 表单id
     * @return 删除的条数
     */
    @Override
    @Transactional
    public Integer deleteFormInfo(String formId) {
        Integer count = 0;
        int formInfoTotal = formInfoMapper.deleteById(formId);
        QueryWrapper<FormModel> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(formId)){
            wrapper.eq("form_id",formId);
            count = formModelMapper.selectCount(wrapper);
        }
        if (formInfoTotal > 0 && count > 0){
            formModelMapper.delete(wrapper);
        }
        return formInfoTotal;
    }

    /**
     * 分页模糊查询表单模型
     *
     * @param params 查询参数
     * @param query  分页参数
     * @return 查询出的列表
     */
    @Override
    public PagerModel<FormInfo> queryFormList(QueryFormInfoTO params, Query query) {
        Page<FormInfo> page = new Page<>(query.getPageNum(), query.getPageSize());
        QueryWrapper<FormInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(params.getFormId())){
            wrapper.lambda().like(FormInfo::getFormId,params.getFormId());
        }
        if (!StringUtils.isEmpty(params.getFormName())){
            wrapper.lambda().like(FormInfo::getFormName,params.getFormName());
        }
        if (params.getFormType() != null){
            wrapper.lambda().eq(FormInfo::getFormType, params.getFormType());
        }
        IPage<FormInfo> formInfoIPage = formInfoMapper.selectPage(page,wrapper);
        return new PagerModel<>(formInfoIPage);
    }

    @Override
    public ReturnVO saveModel(FormInfoExModelArr params) {
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        ReturnVO result = null;
        try {
            String formId = params.getFormId();
            FormInfo formInfo = formInfoMapper.selectById(formId);
            formInfo.setFormInfo(params.getFormInfo());
            formInfo.setUpdateTime(new Date());
            formInfo.setUpdateUser(params.getUpdateUser());
            formInfo.setFormSync(0);
            formInfoMapper.updateById(formInfo);

            List<FormModel> models = params.getModels();
            QueryWrapper<FormModel> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(FormModel::getFormId, formInfo.getFormId());
            formModelMapper.delete(wrapper);
            formModelService.saveBatch(models);

            dataSourceTransactionManager.commit(transactionStatus);
            result = new ReturnVO(ReturnCode.SUCCESS,"保存成功");
        } catch (Exception e) {
            dataSourceTransactionManager.rollback(transactionStatus);
            result = new ReturnVO(ReturnCode.SUCCESS, e.getMessage().toString());
        }
        return result;
    }

    /**
     * 获取所有表单项
     *
     * @param formId 表单id
     * @return
     */
    @Override
    public ReturnVO<List<FormModel>> getFormFieldByFormId(String formId) {
        Map<String,Object> formIdMap = new HashMap<>();
        ReturnVO<List<FormModel>> result = null;
        formIdMap.put("form_id",formId);
        List<FormModel> formInfoList = formModelMapper.selectByMap(formIdMap);
        if (formInfoList.size()>0){
            result = new ReturnVO<>(ReturnCode.SUCCESS,"查询成功",formInfoList);
        } else {
            result = new ReturnVO<>(ReturnCode.FAIL,"查询失败",formInfoList);
        }
        return result;
    }

    @Override
    public List<FormModel> queryTableById(String formId) {
        QueryWrapper<FormModel> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FormModel::getFormId, formId);
        wrapper.lambda().orderByAsc(FormModel::getSort);
        return formModelMapper.selectList(wrapper);
    }

//    @Override
//    public FormInfo queryFormByModelKey(String modelKey) {
//        QueryWrapper<FormInfo> wrapper = new QueryWrapper<>();
//        wrapper.lambda().eq(FormInfo::getModelKey, modelKey);
//        FormInfo formInfo = formInfoMapper.selectOne(wrapper);
//        return formInfo;
//    }

}
